var wxSortPickerView = require('../../wxSortPickerView/wxSortPickerView.js');
var constract = require('../../utils/constract.js');
var comm = require('../../utils/common.js');
var app = getApp();
Page({
  data: {//show已被占用,如需要重命名
    imperfect: false,
    sort: 1,
    isHide: true,
    noAuth: false,
  },
  onShow: function () {
    var that = this;
    if(wx.getStorageSync('noAuth')){
      console.log(wx.getStorageSync('noAuth'))
      that.setData({
        noAuth: wx.getStorageSync('noAuth')
      })
      return;
    }
    app.Verification(function (token) {
      if(wx.showLoading){
        wx.showLoading({
          title:'加载中',
          mask: true,
        })
      }
      wx.request({
        url: constract.index,
        header: { token: token },
        success: function (res) {
          console.log(res);

          if(res.data.code === '23000') {
            that.setData({
              noAuth: true
            })
            return;
          } else {
            that.setData({
              noAuth: false
            })
            wx.removeStorageSync('noAuth');
          }

          var userInfo = res.data.data;
          that.setData({
            userInfo: userInfo
          })

          if(res.data.data.state === 0){ //没有创建名片
            that.setData({
              regState: res.data.data.state
            })
            wx.request({
              url: constract.defaultName, //查看首页的名片信息
              header: { token: token },
              success: function (res) {
                console.log(res);

                app.globalData.nickName = res.data.name;
                app.globalData.avatarUrl = res.data.avatar;

                userInfo.name = app.globalData.nickName;
                userInfo.avatar = app.globalData.avatarUrl;
                
                that.setData({
                  userInfo: userInfo
                })
              }
            })
            that.setData({
              // promptShow: app.globalData.globalAuth, //判断是否授权
              promptShow: true //判断是否授权
            })
          } else {
            var userInfo = res.data.data.user;
            that.setData({
              userInfo: userInfo,
              isHide: true,
            });
          }
        },
        complete:()=>{
          if(wx.hideLoading){
            wx.hideLoading()
          }
        }
      });
      wx.request({
        url: constract.findCollect,
        header: { token: token },
        data: { type: that.data.sort, keyword: '' },
        success: function (res) {
          console.log(res);
          if(res.data.code === '23000'){
            return;
          }
          var data = res.data.data;
          for(var i=0; i<data.length; i++) { // 处理多个公司的情况
            if (data[i].list) {
              for (var j = 0; j < data[i].list.length; j++) {
                data[i].list[j].company = data[i].list[j].company.split(",")[0]
              }
            } else {
              data[i].company = data[i].company.split(",")[0]
            }
          }

          that.setData({
            list: data
          });

          if (that.data.sort == 1) {
            var total = 0;
            for (var i = 0; i < data.length; i++) {
              var obj = data[i];
              var len = obj.list.length;
              total += len;
            };
            that.setData({
              total: total
            });
          }
          // wxSortPickerView.init(data, that);
        }
      })
    })
    app.globalData.url = {
      url: '../details/details',
    }

    console.log(this.data);
  },
  getSwiperIdx(e){
    app.globalData.swiperIdx = e.currentTarget.dataset.swiper;
    wx.switchTab({
      url: '/pages/index/index',
    })
  },
  goAdd: function(){
    this.setData({
      // promptShow: app.globalData.globalAuth, //判断是否授权
      promptShow: true, //判断是否授权
    })
  },
  sort: function (e) { //2按姓名排序 3按公司排序
    var that = this;
    app.Verification(function (token) {
      wx.request({
        url: constract.findCollect,
        header: { token: token },
        data: { type: e.currentTarget.dataset.type, keyword: '' },
        success: function (res) {
          var data = res.data.data;
          data["sort"] = e.currentTarget.dataset.type;

          that.setData({
            list: data,
            sort: e.currentTarget.dataset.type,
            isHide: true
          });

          wxSortPickerView.init(data, that);
        }
      })
    })
  },

  collected: function(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    var collectState = e.currentTarget.dataset.type;
    var uid = e.currentTarget.dataset.uid;

    wx.showModal({
      title: '提示',
      content: '确认删除此名片？',
      success: function(res) {
        if (res.confirm) {
          app.Verification(function (token) {
            wx.request({
              url: constract.collectionAddOrEdit, // 取消收藏和重新收藏接口
              header: { token: token },
              data: { collection_uid: uid, is_delete:collectState, cardId: id },
              success: function (res) {
                if (res.data.code == 12000) {
                  wx.request({
                    url: constract.findCollect,
                    header: { token: token },
                    data: { type: that.data.sort, keyword: '' },
                    success: function (res) {
                      var data = res.data.data;
                      that.setData({
                        list: data
                      });
      
                      if (that.data.sort == 1) {
                        var total = 0;
                        for (var i = 0; i < data.length; i++) {
                          var obj = data[i];
                          var len = obj.list.length;
                          total += len;
                        };
                        that.setData({
                          total: total
                        });
                      }
                      wxSortPickerView.init(data, that);
                    }
                  })
                };
              }
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },

  deleCard: function (e) {
    var that = this;
    var id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '提示',
      content: '确认删除此名片？',
      success: function(res) {
        if (res.confirm) {
          app.Verification(function (token) {
            wx.request({
              url: constract.cardDelete,
              header: { token: token },
              data: { id: id },
              success: function (res) {
                if (res.data.code == 12000) {
                  wx.request({
                    url: constract.findCollect,
                    header: { token: token },
                    data: { type: that.data.sort, keyword: '' },
                    success: function (res) {
                      var data = res.data.data;
                      that.setData({
                        list: data
                      });
      
                      if (that.data.sort == 1) {
                        var total = 0;
                        for (var i = 0; i < data.length; i++) {
                          var obj = data[i];
                          var len = obj.list.length;
                          total += len;
                        };
                        that.setData({
                          total: total
                        });
                      }
                      wxSortPickerView.init(data, that);
                    }
                  })
                };
              }
            })
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  goGroup: function (e) {
    wx.navigateTo({
      url: '../details/group/group?id=' + e.currentTarget.dataset.id + '&group_name=' + e.currentTarget.dataset.group_name + '&type=' + e.currentTarget.dataset.type + '&ouid='+e.currentTarget.dataset.ouid
    });
  },
  goMark: function (e) {
    wx.navigateTo({
      url: '../input-card/mark/mark?id=' + e.currentTarget.dataset.id + '&state=' + e.currentTarget.dataset.type + '&name='+e.currentTarget.dataset.name
    });
  },
  goDetail: function (e) {
    wx.navigateTo({
      url: app.globalData.url.url + '?id=' + e.currentTarget.dataset.id + '&type=' + e.currentTarget.dataset.type + '&ouid=' + e.currentTarget.dataset.ouid
    });
  },
  call: function (e) {
    var arrPhone = [];
    var phone = e.currentTarget.dataset.phone;
    if (phone.indexOf(',') > -1) {
      arrPhone = phone.split(',');
    } else {
      arrPhone.push(phone);
    }
    if (phone) {
      wx.showActionSheet({
        itemList: arrPhone,
        success: function (res) {
          wx.makePhoneCall({
            phoneNumber: arrPhone[res.tapIndex],
            success: function(){
            },
            fail: function(err){
              console.log(err);
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '该名片暂时没有填写手机号码',
        success: function (res) {
          if (res.confirm) {
          } else if (res.cancel) {
          }
        }
      })
    }
  },
  wxSortPickerViewItemTap: function (e) {
  },
  touchstart: function (e) {
    var that = this;
    var list = this.data.list;
    var id = ''+e.currentTarget.dataset.id + e.currentTarget.dataset.type;
    if (that.data.sort !== 1) {
      if (e.touches.length == 1) {
        for (var i = 0; i < list.length; i++) {
          if (''+list[i].id + list[i].type !== id) {
            list[i].txtStyle = "right:-520rpx";
            list[i].contentStyle = "right:0rpx";
          }
        };
        this.setData({
          startX: e.touches[0].clientX,
          list: list
        })
        wxSortPickerView.init(that.data.list, that);
      }
    } else {
      if (e.touches.length == 1) {
        for (var i = 0; i < list.length; i++) {
          for (var j = 0; j < list[i].list.length; j++) {
            if (''+list[i].list[j].id + list[i].list[j].type !== id) {
              list[i].list[j].txtStyle = "right:-520rpx";
              list[i].list[j].contentStyle = "right:0rpx";
            }
          }
        };
        this.setData({
          startX: e.touches[0].clientX,
          list: list
        })
      }
    }
  },
  touchend: function (e) {
    var that = this;
    if (that.data.sort !== 1) {
      if (e.changedTouches.length == 1) {
        var endX = e.changedTouches[0].clientX;
        var disX = this.data.startX - endX;
        var txtStyle = disX > 30 ? "right:-440rpx" : "right:-520rpx";
        var contentStyle = disX > 30 ? "right:220px" : "right:0rpx";
        var id = ''+e.currentTarget.dataset.id + e.currentTarget.dataset.type;
        var list = this.data.list;
        for (var i = 0; i < list.length; i++) {
          if (''+list[i].id + list[i].type == id) {
            list[i].txtStyle = txtStyle;
            list[i].contentStyle = contentStyle;
            this.setData({
              list: list
            })
          }
        }
        wxSortPickerView.init(that.data.list, that);
      }
    } else {
      if (e.changedTouches.length == 1) {
        var endX = e.changedTouches[0].clientX;
        var disX = this.data.startX - endX;
        var txtStyle = disX > 30 ? "right:-440rpx" : "right:-520rpx";
        var contentStyle = disX > 30 ? "right:220px" : "right:0rpx";
        var id = '' + e.currentTarget.dataset.id + e.currentTarget.dataset.type;
        var list = this.data.list;
        for (var i = 0; i < list.length; i++) {
          for (var j = 0; j < list[i].list.length; j++) {
            if (''+list[i].list[j].id + list[i].list[j].type == id) {
              list[i].list[j].txtStyle = txtStyle;
              list[i].list[j].contentStyle = contentStyle;
              this.setData({
                list: list
              })
            }
          }
        }
      }
    }
  },
  scan: function () {
    var userInfo = this.data.userInfo;
    if (userInfo.state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
            })
          }
        }
      })
    } else {
      wx.showLoading({
        title: '扫描中',
        mask: true,
        success: function(){
          wx.scanCode({
            success: (res) => {
              wx.hideLoading();
              wx.navigateTo({
                url: res.path
              });
            },
            complete: () => {
              wx.hideLoading();
            }
          })
        }
      })
    }
  },

  choseUpload: function () {
    var that = this;
    comm.ocrImg(['album', 'camera'],that,constract.scanCard,'card',1) //名片扫描->1
  },

  choseWxUpload: function(){
    var that = this;
    comm.ocrImg(['album', 'camera'],that,constract.wxScan,'card',2) //微信截图扫描->2
  },

  addCard: function () {
    var that = this;
    var userInfo = this.data.userInfo;
    if (userInfo.state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
            })
          }
        }
      })
    } else {
      wx.showActionSheet({
        itemList: ['手动输入名片', '从相册导入'],
        success: function (res) {
          if (res.tapIndex === 0) {
            wx.navigateTo({
              url: '/pages/input-card/input-card?mInput=1&uploadType=0',
            })
          };
          if (res.tapIndex === 1) {
            wx.showActionSheet({
              itemList: ['名片导入', '微信截图导入'],
              success: function (res) {
                if(res.tapIndex === 0){
                  console.log(res.tapIndex);
                  that.choseUpload();
                } 

                if(res.tapIndex === 1) {
                  console.log(res.tapIndex);
                  that.choseWxUpload();
                }
              }
            })
          }
        },
        fail: function (res) {
        }
      })
    }
  },
  doGroup: function() {
    var userInfo = this.data.userInfo;
    if (userInfo.state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
            })
          }
        }
      })
    } else {
      wx.navigateTo({
        url: "./card-group/card-group"
      })
    }
  },
  qrCode: function(e) {
    var userInfo = this.data.userInfo;
    var avatar = e.currentTarget.dataset.avatar;
    var name = e.currentTarget.dataset.name;
    var id = e.currentTarget.dataset.id;
    var ouid = e.currentTarget.dataset.ouid;

    if (userInfo[0].state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + avatar + '&name=' +name+'&id='+id,
            })
          }
        }
      })
    } else {
      wx.navigateTo({
        url: "../code/code?avatar="+avatar+"&name="+name+"&id="+id+'&ouid='+ouid
      })
    };      
  },
  share: function () {
    var userInfo = this.data.userInfo;
    if (userInfo.state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
            })
          }
        }
      })
    }
  },
  manger: function () {
    var userInfo = this.data.userInfo;
    if (userInfo.state == 0) {
      wx.showModal({
        title: '您还没有名片',
        content: '创建自己的名片，让大家认识你',
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/add-card/add-card?avatar=' + userInfo.avatar + '&name=' + userInfo.name,
            })
          }
        }
      })
    } else {
      this.setData({
        isHide: false
      });
    }
  },
  cancel: function () {
    this.setData({
      isHide: true
    });
  },
  onShareAppMessage: function (res) {
    console.log(res);
    var id = res.target.dataset.cardid;
    var uid = res.target.dataset.uid;
    
    return {
      imageUrl: '/images/mm_share.jpg',
      title: '幸会！这是我名片请惠存！',
      path: '/pages/partner/partner?id='+id+'&uid='+uid
    }
  },

  promptCancel: function(){
    this.setData({
      promptShow: false
    })
  },
  hideAuth: function(){
    this.setData({
      getAuth: false
    })
  },
  onGotUserInfo: function(e){//允许
    console.log(e);
    if(e.detail.errMsg === "getUserInfo:fail auth deny") {
      this.setData({
        getAuth: true
      })
    } else {
      wx.removeStorageSync('noAuth');
      wx.navigateTo({
        url: `/pages/add-card/add-card?avatar=${e.detail.userInfo.avatarUrl}&name=${e.detail.userInfo.nickName}`
      })
    }
  }
})